import React, { useEffect, useState } from 'react'
import { Input, message } from 'antd'
import type { SearchProps } from 'antd/es/input/Search'
import { CLEAR_SEARCH_KEYWORD } from '@/common/constant'

const Search: React.FC<{ handleKeyword: Function }> = (props) => {
    const { handleKeyword } = props

    const [keyword, setKeyword] = useState('')

    const [messageApi, contextHolder] = message.useMessage()

    const onSearch: SearchProps['onSearch'] = (value) => {
        let keyword = value.trim()
        if (!keyword) {
            return messageApi.open({
                type: 'warning',
                content: '搜索关键字不能为空',
            })
        }
        // 将输入框的值传递回去
        handleKeyword(keyword)
    }

    const onChange = (e: any) => {
        setKeyword(e.target.value)
    }

    useEffect(() => {
        PubSub.subscribe(CLEAR_SEARCH_KEYWORD, () => setKeyword(''))
    }, [])

    return <>
        {contextHolder}
        <Input.Search
            style={{ minWidth: 300 }}
            variant="filled"
            placeholder="请输入搜索内容"
            value={keyword}
            onSearch={onSearch}
            onChange={onChange}
            enterButton
        />
    </>
}

export default Search